// components/approve/approve.js
const req = require('../../utils/request');
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tableid: {
      type: String,
      observer(val){
        this.getUser();
      }
    },
    rowid:{
      type: String
    },
    isNew: {
      type: Boolean
    },
    //隐藏按钮、输入框
    hideBtn: {
      type: Boolean
    }
  },


  /**
   * 监听数据
   */
  observers:{
    async 'tableid, rowid, isNew'(tableid,rowid,isNew){
      await this.getApprovalList();
      if (tableid && rowid){
        if (isNew) {

          let obj = {};

          if (this.data.approveProcess){
            //231030 yan 修改
            // obj.sbmBtnStatus = 3;
            // if (this.data.approveProcess.is_choose)obj.sbmFlag = true;
            obj.sbmBtnStatus = 1;
            if (this.data.approveProcess.is_choose){
              obj.sbmFlag = true;
              obj.sbmBtnStatus = 3;
            }
          }else {
            obj.sbmBtnStatus = 0;
          }
          this.setData(obj);

          return
        }
        this.getApprovalProcess();
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    //提交审批时选择
    aprList: [], //审批人用户信息
    copyList: [], //抄送人用户信息
    nextList: [], //下一审批人选择信息

    selectFlag: false,  //用户选择弹出
    userList: [],   //用户列表选项

    curType: '',  //用户选择类型标识-aprList审批人、copyList抄送人

    // aprGroup: [],   //自由审批分组
    // stepGroup: [],  //固定审批分组
    logsGroup: [],    //自由审批固定审批

    // aprFlag: true,  //审批信息展开收起标识
    // copyFlag: true,  //抄送信息展开收起标识

    // aprData: [],    //审批信息
    // copyData: [],    //抄送信息

    approveProcess: null,  //审批流程信息
    process_id: null,   //审批流程id

    sbmBtnStatus: 0,  //提交审批显示按钮：0 不显示按钮，1 显示提交审批按钮，2 取消按钮 3 确定审批按钮
    sbmFlag: false,  //自由审批选择界面
    aprUserFlag: false,  //是否当前用户可操作审批
    approveFlag: true,  //审批意见框显示

    shMark: '',  //审批意见

    showSignature: false, //签名组件弹窗
    watermark: [{
      content: '$time$',
      font: '24px serif',
      position: {
        bottom: 15,
        left: 15
      }
    },
      {
        content: '$location$',
        font: '22px serif',
        position: {
          bottom: 42,
          left: 15
        }
      },],    //签名水印

    system_id: wx.getStorageSync('system_id') || 1164,  //231215 yan 图片字段只返回文件名时，需要系统号拼接图片地址
    baseURL: req.baseURL,

    isShowInput: false, //控制输入栏
    curLogRow: null,  //当前评论的审批记录行

    user_id: wx.getStorageSync('user_id'),  //用户id
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //选择用户
    bindadd(e){
      let {type} = e.currentTarget.dataset;
      this.setData({
        curType: type,selectFlag: !this.data.selectFlag
      });
    },
    //展开收起分组
    toggleShow(e){
      let {index,type} = e.currentTarget.dataset;
      // this.setData({[`${type}[${index}].showFlag`] : !this.data[type][index].showFlag})
      this.setData({[`logsGroup[${index}].showFlag`] : !this.data['logsGroup'][index].showFlag})

    },
    //展开收起审批内容
    bindtoggle(e){
      let {type,index,cur_ind,par_ind,cur_type} = e.currentTarget.dataset,
        obj = {};
      if (type === 'aprGroup') {
        // obj = {[`${type}[${par_ind}].${cur_type}`]: !this.data[type][par_ind][cur_type]}
        obj = {[`logsGroup[${par_ind}].${cur_type}`]: !this.data['logsGroup'][par_ind][cur_type]}
      }else {
        // obj = {[`${type}[${par_ind}].process[${cur_ind}].flag`]: !this.data[type][par_ind].process[cur_ind].flag};
        obj = {[`logsGroup[${par_ind}].process[${cur_ind}].flag`]: !this.data['logsGroup'][par_ind].process[cur_ind].flag};
      }

      this.setData(obj);
    },
    //选中用户
    select(e){
      let detail = e.detail,
        type = this.data.curType,
        list = this.data[type],
        obj = {
          selectFlag:false
        };
      console.log(type);
      if ((type === 'copyList' && !list.some(item =>item.id === detail.id)) || (['userList','nextList'].includes(type))  ){
        list.push(detail);
        obj[type] = list;
      }
      this.setData(obj);
      if (type === 'transfer') this.transferApprove(detail)
    },
    //删除选中用户
    binddel(e){
      let dataset = e.currentTarget.dataset,
        type = dataset.type,
        index = dataset.index,
        list = this.data[type];
      list.splice(index,1);
      this.setData({
        [type]: list
      })
    },
    //转交审批
    transferApprove(detail){
      wx.showModal({
        title: '转交',
        content: `确定转交该审批给${detail.name}？`,
        success: res =>{
          if (res.confirm){
            wx.showLoading({mask: true})
            //转交审核
            this.submitApproval('转交','',[detail.id],[detail.name]).then(() => wx.hideLoading())
          }
        }
      })
    },

    //提交审批按钮
    bindSmbBtn(e){
      let type = e.currentTarget.dataset.type;
      if (type == 1){ //提交审批
        this.toggleApprove(1);
      }
      if (type == 2){ //取消按钮
        if (this.data.isNew){
          this.triggerEvent(
            'approve'
          );
          return;
        }
        this.setData({
          sbmBtnStatus: 1,
          sbmFlag: false
        });
      }
      if (type == 3){ //确定提交审批

        wx.showLoading({mask: true})
        this.submitFreeApproval().then(()=>{
          this.getApprovalProcess();
          this.triggerEvent('approve');

        })
      }
    },

    // 双向绑定 报警告处理
    inputIpt(e) {},

    //审批操作
    bindApprove(e){
      let state = e.currentTarget.dataset.state;
      //签名
      if (this.data.lastProcess?.need_upload_sign_pic){
        this.setData({showSignature:true,curState: state});
        return
      }
      wx.showLoading({mask: true});
      this.submitApproval(state,this.data.shMark).then(() => wx.hideLoading());
    },
    //签名完操作
    onSign({detail}){
      this.setData({showSignature:  false});
      wx.showLoading({mask: true});
      wx.$uploadReq(detail).then(res =>{
        if (res.response.errcode != 0) {
          wx.$toast(res.errmsg);
          return
        }
        let data = res.data.row[0];

        this.submitApproval(this.data.curState,this.data.shMark,[],[],data?.filename).then(() => {
          wx.hideLoading();
          this.data.curState = null;
        });
      })
    },
    onSignCancel(){
      this.setData({showSignature:  false});
    },

    //切换审批按钮
    async toggleApprove(type){
      let {approveProcess} = this.data;

      if (!approveProcess) { //获取审批信息
        await this.getApprovalList();
        approveProcess = this.data.approveProcess;
      }

      if (approveProcess.is_choose){ //自由审批
        this.setData({
          sbmBtnStatus: 3,
          sbmFlag: true
        });
      } else {
        this.submitApproval('提交')
      }

    },
    //提交固定审批
    submitApproval(state,mark,nextids = [],nextnames = [],sign_pic) { //审批状态
      let {tableid,rowid,approveProcess,process_id,nextList,lastProcess} = this.data,
        proid = approveProcess && approveProcess.process_id || process_id,
        post = {
          "table_id": tableid,
          "row_id": rowid ,
          "sh_state": state,
          "next_sh_id":"",
          "next_sh_name":"",
          "sh_mark": mark || "",
          process_id: '',
          sign_pic
        };
      let nextid = [...nextids],
        nextname = [...nextnames]
      if (lastProcess?.choose_able && nextList.length){
        nextList.forEach(item => {
          nextid.push(item.id);
          nextname.push(item.name)
        });
      }
      nextid.length && (post.next_sh_id = nextid.join(','))
      nextname.length && (post.next_sh_name = nextname.join(','))

      if (state.indexOf('提交') >= 0){post.process_id = proid}
      return new Promise(resolve => {
        wx.$post(3,'Approval_process/update_approval_process_log',post).then(res=>{
          this.getApprovalProcess();
          this.triggerEvent('approve');
          resolve();
        });
      });

    },
    //提交自由审批
    submitFreeApproval(rid){
      return new Promise(resolve => {
        let {aprList, copyList, approveProcess,tableid, rowid,process_id} = this.data,
          post = {
            "process_id": approveProcess && approveProcess.process_id || process_id,
            "table_id": tableid,
            "row_id": rid || rowid,
            "apply_mark": '',
            "apply_attachment_list": '',
            "apply_approver_list": '',
            "apply_cc_list": ''
          },
          aprArr = [],
          copyArr = [];

        if (aprList.length === 0){

          wx.$toast('请先选择审批人!');

          return
        }

        wx.$each(aprList,(i,item)=>{
          aprArr.push(item.id);
        });
        wx.$each(copyList,(i,item)=>{
          copyArr.push(item.id);
        });

        post.apply_approver_list = aprArr.join(',');
        post.apply_cc_list = copyArr.join(',');
        wx.$post(3,'Approval_process/create_approval_process_log2',post).then(res=>{
          resolve();
        });
      })
    },


    //获取审批列表
    getApprovalList(){
      let {rowid,tableid} = this.data,
        post = {
        limit: 10000,
        oby: "process_id desc",
        page: 1,
        SearchWhere: [
          {
            "CompareWith": "table_id",
            "Operator": "=",
            "CompareValue": tableid,
            "or": 0
          },
          {
            "CompareWith": "status",
            "Operator": "=",
            "CompareValue": true,
            "or": 0
          }
        ]
      };
      return new Promise(resolve => {
        wx.$post(3,'Approval_process/query_approval_process',post).then(res=>{
          if (res.errcode != 0)return;
          let list = [],
            data = res.data.row || [];
          this.setData({approveListAll: data})
          wx.$each(data,async (i,item) =>{
            if(['null',null,'undefined',undefined,''].includes(item.combination_query_json)){
              list.push(item);
              return
            }
            if (await this.approveFilter(rowid,item.combination_query_json)){
              list.push(item);
            }
          });
          if (list[0]){
            let info = list[0],
              isChoose = info.is_choose,
              process_id = info.process_id,
              process_name = info.process_name,
              obj = {};
            obj.approveProcess = info;//第一条审批数据
            obj.approveList = list;
            this.setData(obj);

          }else {
            wx.$toast('没有可提交的审批流程，请设置审批流程！');
          }
          resolve();
        });
      })
    },
    //判断审批
    async approveFilter(rowid,query){
      let tableid = this.data.tableid,
        ARR = this.eachFilter(tableid,[JSON.parse(query)]),
        where = {
          "CompareWith": tableid + '.row_id',
          "Operator": '=',
          "CompareValue": rowid,
          "or": 0
        };
      ARR.push(where);
      let post = {
          limit: 1,
          oby: tableid + ".row_id desc",
          page: 1,
          table_id: tableid,
          SearchWhere: ARR
        },
        flag = false;
      await wx.$post(3,'DynamicQuery/query_dynamic_v1',post).then(res =>{
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        if (data.length === 0)return;
        flag = true;
      });
      return flag;
    },
    //级联对象筛选条件转为同级数组
    eachFilter(arr){
      let ARR = [],
        tableid = this.data.tableid;
      wx.$each(arr,(i,item) =>{
        let filters = item.filters,
          type = item.type;
        wx.$each(filters,function (ind,ite) {
          let compareWith = (ite.fieldName || ite.CompareWith);
          compareWith = compareWith.indexOf('.') >= 0 ? compareWith : (tableid + '.' + compareWith);
          let obj = {
            "CompareWith": compareWith,
            "Operator": (ite.operator || ite.Operator),
            "CompareValue": (ite.value || ite.CompareValue || '').toString(),
            "or": (type.toLocaleString() === "and" ? 0 : 1)
          };
          ARR.push(obj);
        });
        ARR = ARR.concat(this.eachFilter(item.children || []));
      });
      return ARR;
    },

    //获取审批内容
    getApprovalProcess() {
      let {tableid,rowid,approveList} = this.data,
        post = {
          "page": 1,
          "limit": 1000,
          "oby": "input_time,group_id,step,log_row_id",
          "SearchWhere": [
            {
              "CompareWith": "table_id",
              "Operator": "=",
              "CompareValue": tableid,
              "or": 0
            },
            {
              "CompareWith": "row_id",
              "Operator": "=",
              "CompareValue": rowid,
              "or": 0
            },
            /*{
              "CompareWith": "1",
              "Operator": "=",
              "CompareValue": "(CASE WHEN step>1 AND sh_state='待审' THEN 0 ELSE 1 END)",
              "or": 0
            }*/
          ]
        };

      wx.$post(3,'Approval_process/query_approval_process_log_group',post).then(async res=>{
        if (res.errcode != 0)return;
        let row = res.data.row || [],
          lastGroup = row[row.length -1],
          data = lastGroup && lastGroup.process;
        lastGroup && (lastGroup.showFlag = true)
        let obj = {};
        if (lastGroup && data && data.length > 0) {//有数，代表已提交
          let last = data[data.length-1];
          this.isApprovalUser(last.end_able);

          obj.lastProcess = last;
          // obj.aprData = data;
          obj.process_id = last.process_id;
          obj.sbmFlag = false;

          // let approveInfo = approveList?.find(item => item.process_id === last.process_id);

          this.eachGroups(row);

          /*let stepGroup = this.formatLogs(row);
          obj.stepGroup = stepGroup
          //固定审批，格式化审批记录 240228 注释
          if (!approveInfo?.is_choose) {
            let stepGroup = this.formatLogs(row);
            obj.stepGroup = stepGroup
          }else {
            obj.aprGroup = row; //同意或提交后不可重新提交
            console.log(lastGroup);
            if (lastGroup.process_ed_state === '已同意' || lastGroup.process_ed_state ==='已提交' || lastGroup.process_ed_state === '已重新提交'){
              obj.sbmBtnStatus = 0;
              this.triggerEvent(
                'apr_state', true
              );
            }else {
              obj.sbmBtnStatus = 1;
              this.triggerEvent(
                'apr_state', false
              );
            }
          }*/

         /* //是否已结束
          if (last.end_able) {

          }else {

          }

          //是否可自由选择审批人
          if (last.choose_able) {

          }else {

          }

          //是否可结束整个流程
          if (last.is_end){

          } else {

          }*/
        }else { //没有数可提交
          await this.getApprovalList();
          if (this.data.approveProcess){
            obj.sbmBtnStatus = 1;
            if (this.data.approveProcess.is_choose){
              obj.sbmFlag = true;
              obj.sbmBtnStatus = 3;
            }
          }else {
            obj.sbmBtnStatus = 0;
          }
        }
        this.setData(obj,()=>{
          wx.hideLoading();
        })

      });
    },
    //获取当前人员是否可操作审批
    isApprovalUser (isEnd){ //是否已结束,已结束不可操作
      let {tableid,rowid} = this.data,
        post = {
          "table_id": tableid,
          "row_id": rowid
        };
      wx.$post(3,'Approval_process/get_approval_process_operate',post).then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row || [],
          is_operate = data[0] && data[0].is_operate;
        if (is_operate && !isEnd){  //当前用户审批
          this.setData({
            aprUserFlag: true
          })
        } else {  //不可审批
          this.setData({
            aprUserFlag: false
          })
        }
      });
    },

    //获取用户列表
    getUser(){
      wx.$get(3,'BaseTable/select_user').then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        this.setData({userList: data});
      })
    },

    //循环审批分组
    async eachGroups(data){
      let {approveListAll} = this.data,
        list = [],obj = {};
      for (let index in data){
        let item = data[index];
        let process_id = item.process[0]?.process_id;
        let approveInfo = approveListAll?.find(item => item.process_id === process_id);

        if (approveInfo.is_choose){
          item.isFree = true;
          list.push(item)
        } else {
          list.push(await this.formatFreeLogs(item,index,data))
        }
      }
      /*data.forEach((item,index) =>{
        let process_id = item.process[0]?.process_id;
        let approveInfo = approveListAll?.find(item => item.process_id === process_id);
        console.log(approveInfo);
        if (approveInfo.is_choose){
          item.isFree = true;
          list.push(item)
        } else {
          list.push(this.formatFreeLogs(item,index,data))
        }
      });*/

      let lastGroup = list[list.length -1];
      if (lastGroup.isFree){  //自由审批
        if (['已同意','已提交','已重新提交'].includes(lastGroup.process_ed_state)){
          obj.sbmBtnStatus = 0;
          this.triggerEvent('apr_state', true);
        }else {
          obj.sbmBtnStatus = 1;
          this.triggerEvent('apr_state', false);
        }
      }else { //固定审批
        let lastProcess = lastGroup?.process,
          last = lastProcess?.[lastProcess.length-1];
        //最后一条数据审核完成且审核通过则审批结束
        if (last.end_able && last.endStatus === '已同意') list[list.length-1].end = true;

        //当前审批状态为已同意或已提交的不能重新提交审批
        if ([ '已同意','已提交','已重新提交'].includes(last.endStatus)) {
          obj.sbmBtnStatus = 0;
          this.triggerEvent('apr_state', true);
        }else {
          obj.sbmBtnStatus = 1;
          this.triggerEvent('apr_state', false);
        }
      }
      this.setData({...obj,logsGroup: list})
    },
    //固定审批
    async formatFreeLogs(ite,ind,data){
      let obj = {};
      let logs = [],
        {process,input_time} = ite,
        groups = this.groupBy(process,'group_id');  //按组号分类
      let keys = Object.keys(groups)
      for (let i = 0; i<keys.length;i++){
        let item = keys[i],arr = groups[item],obj = {next: []};
        for (let ind = 0; ind <arr.length ; ind ++){
          let ite = arr[ind];

          let {sh_name,sh_state,sh_mark,sh_time,next_sh_name,next_sh_state,next_sh_mark,next_sh_time,process_name,process_step_name,end_able,sign_type,sign_pic,log_row_id} = ite;
          //多条数据只需判断第一条数据
          if (!ind){
            obj = {...obj,process_step_name,sign_type,end_able,process_all_total: arr.length,process_ed_total: 0,endStatus: sh_state}
          }
          //有下一步操作
          if (next_sh_name)  {
            next_sh_time && obj.process_ed_total++;
            let comments = await this.findCommentById(log_row_id);
            console.log(comments);
            obj.next.push({next_sh_name,next_sh_state,next_sh_mark,next_sh_time,sign_pic,log_row_id,comments})
          }
          //审核结束 且 前一条数据没有拒绝 且 当前数据已审核的赋值
          if (end_able && obj.endStatus !== '已拒绝' && next_sh_state){
            obj.endStatus = next_sh_state;
            obj.endShTime = next_sh_time;
            obj.endProcess = process_name;
          }
        }

        //有下一步数据
        obj.next.length && logs.push(obj);
      }
      obj = {process:logs,input_time: ite.input_time,showFlag: ind == data.length-1,isFree: false};
      return obj;

      /*Object.keys(groups).forEach(item =>{
        let arr = groups[item],
          obj = {next:[]};
        //遍历同一组数据，
        arr.forEach((ite,ind) =>{
          let {sh_name,sh_state,sh_mark,sh_time,next_sh_name,next_sh_state,next_sh_mark,next_sh_time,process_name,process_step_name,end_able,sign_type,sign_pic,log_row_id} = ite;
          //多条数据只需判断第一条数据
          if (!ind){
            obj = {...obj,process_step_name,sign_type,end_able,process_all_total: arr.length,process_ed_total: 0,endStatus: sh_state}
          }
          //有下一步操作
          if (next_sh_name)  {
            next_sh_time && obj.process_ed_total++;
            obj.next.push({next_sh_name,next_sh_state,next_sh_mark,next_sh_time,sign_pic,log_row_id})
          }
          //审核结束 且 前一条数据没有拒绝 且 当前数据已审核的赋值
          if (end_able && obj.endStatus !== '已拒绝' && next_sh_state){
            obj.endStatus = next_sh_state;
            obj.endShTime = next_sh_time;
            obj.endProcess = process_name;
          }

        });
        //有下一步数据
        obj.next.length && logs.push(obj);
      });
      obj = {process:logs,input_time: ite.input_time,showFlag: ind === data.length-1,isFree: false};
      return obj;*/
    },
    //格式化固定审批记录 data: 接口返回数据集--240228 注释
    /*formatLogs(data){
      let list = [];
      data.forEach((ite,ind) =>{
        let logs = [],
          {process,input_time} = ite,
          groups = this.groupBy(process,'group_id');  //按组号分类
        Object.keys(groups).forEach(item =>{
          let arr = groups[item],
            obj = {next:[]};
          //遍历同一组数据，
          arr.forEach((ite,ind) =>{
            let {sh_name,sh_state,sh_mark,sh_time,next_sh_name,next_sh_state,next_sh_mark,next_sh_time,process_name,process_step_name,end_able,sign_type} = ite;
            //多条数据只需判断第一条数据
            if (!ind){
              obj = {...obj,process_step_name,sign_type,end_able,process_all_total: arr.length,process_ed_total: 0,endStatus: sh_state}
            }
            //有下一步操作
            if (next_sh_name)  {
              next_sh_time && obj.process_ed_total++;
              obj.next.push({next_sh_name,next_sh_state,next_sh_mark,next_sh_time})
            }
            //审核结束 且 前一条数据没有拒绝 且 当前数据已审核的赋值
            if (end_able && obj.endStatus !== '已拒绝' && next_sh_state){
              obj.endStatus = next_sh_state;
              obj.endShTime = next_sh_time;
              obj.endProcess = process_name;
            }

          });
          //有下一步数据
          obj.next.length && logs.push(obj);
        });
        list.push({process:logs,input_time: ite.input_time,showFlag: ind === data.length-1})
      })
      let lastProcess = list[list.length-1]?.process,
        last = lastProcess?.[lastProcess.length-1];
      //最后一条数据审核完成且审核通过则审批结束
      if (last.end_able && last.endStatus === '已同意'){
        list[list.length-1].end = true;
      }
      //当前审批状态为已同意或已提交的不能重新提交审批
      if ([ '已同意','已提交','已重新提交'].includes(last.endStatus)) {
        this.setData({sbmBtnStatus: 0})
        this.triggerEvent(
          'apr_state', true
        );
      }else {
        this.setData({sbmBtnStatus: 1})
        this.triggerEvent(
          'apr_state', false
        );
      }
      /!*!//同意后不可重新提交、拒绝后可重新提交
      if ((last.end_able && last.endStatus === '已拒绝') || ![ '已同意','已提交','已重新提交'].includes(last.sh_state)){
        // $('#getApproval').show();
      }else {
        // $('#getApproval').hide();
        // $('#editBtn').hide();
      }*!/
      console.log(list);
      return list
    },*/

    // 审批记录分组
    groupBy(arr,key){
      return arr.reduce((prev,curr)=>{
        (prev[curr[key]] = prev[curr[key]] || []).push(curr);
        return prev;
      },{})
    },

  //  预览签名
    previewImg(e){
      let { src, } = e.currentTarget.dataset;
      let { system_id,baseURL } = this.data,
        imgs = [`${baseURL}/files/${system_id}/${src}`];
      wx.previewImage({
        current: imgs[0],
        urls: imgs
      })
    },


    //点击出现输入框
    showInput: function(e) {
      let {id,ind,cur_ind,par_ind} = e.currentTarget.dataset,
        {logsGroup} = this.data;
      let row = logsGroup[par_ind].process[cur_ind].next[ind];

      this.setData({
        isShowInput: true,
        curLogRow: row
      })
    },

    //隐藏输入框
    onHideInput: function() {
      this.setData({
        isShowInput: false,curLogRow: null
      })
    },
    bindInputMsg(){},

    onSubmitComment(){
      let {inputmessage,curLogRow,logsGroup} = this.data;
      wx.showLoading();
      this.updateComment(curLogRow.log_row_id,inputmessage).then(errcode =>{

        if (errcode != 0) return
        this.setData({isShowInput: false})
        wx.$toast('提交成功');
        this.getCommentList().then(res =>{
          if (res.errcode != 0) return;
          this.data.commentList = res.data.row || [];
          this.findCommentById(curLogRow.log_row_id).then(arr => {
            curLogRow.comments = arr;
            this.setData({logsGroup})
          })
        })
      })
    },

    //获取评论
    getCommentList (){
      let url = 'Approval_process/approval_process_log_comment',
        {tableid,rowid} = this.data,
        post = {
          table_id: tableid,
          row_id: rowid
        };
      return wx.$get(3,url,post).then(res => res)
    },
  //  查找评论
    findCommentById(log_row_id){
      return new Promise(async resolve => {
        let {commentList} = this.data;
        if (!commentList){
          wx.showLoading();
          await this.getCommentList().then(res =>{
            if (res.errcode != 0) return;
            wx.hideLoading();
            commentList = res.data.row || [];
            this.setData({commentList})
          })
        }
        let arr = commentList?.filter(item => item.log_row_id === log_row_id && item.comment_row_id);
        resolve(arr);
      })
    },

  //  提交评论
    updateComment(id,mark){
      let url = 'Approval_process/approval_process_log_comment',
        post = [
          {
            "log_row_id": id,
            "comment": mark
          }
        ];
      return wx.$post(3,url,post).then((res) =>{
        return res.errcode

      })
    },

  //  删除评论
    bindDelComment(e){
      let {id} = e.currentTarget.dataset,
        {curLogRow,logsGroup} = this.data
      wx.showModal({
        title: '删除评论',
        content: '确定删除该评论？',
        confirmText: '确定',
        success: (res) => {
          if(res.confirm) {
            wx.showLoading({mask: true})
            this.delComment(id).then(res =>{
              wx.hideLoading();
              if (res.errcode != 0) return;
              wx.$toast('删除成功');
              this.getCommentList().then(res =>{
                if (res.errcode != 0) return;
                this.data.commentList = res.data.row || [];
                this.findCommentById(curLogRow.log_row_id).then(arr => {
                  curLogRow.comments = arr;
                  this.setData({logsGroup,curLogRow})
                })
              })
            })
          }
        },
      })
    },
    delComment(id){
      let url = `Approval_process/approval_process_log_comment`;
      return wx.$del(3,url,[id]).then(res => res);
    },

  //  显示评论
    showCommentPopup(e){
      let {ind,cur_ind,par_ind} = e.currentTarget.dataset,
        {logsGroup} = this.data;
      let row = logsGroup[par_ind].process[cur_ind].next[ind];

      this.setData({
        showComment: true,
        curLogRow: row
      })
    },
  //  隐藏评论
    hideCommentPopup(){
      this.setData({showComment: false,curLogRow: null})
    }
  }
})
